var net = require('net');    //引入网络模块
var HOST = 'localhost';     //定义服务器地址
var PORT = process.argv[2] || 8146;            //定义端口号

var Faye = require('faye')
var client = new Faye.Client('http://' + HOST + ':3344/events')

console.info('Server is running on port ' + PORT);

//创建TCP服务器
var server = net.createServer(function (socket) {
    var info = socket.remoteAddress + ':' + socket.remotePort;
    console.log('Connected to ' + info);

    //监听数据接收事件
    socket.on('data', function (data) {
        console.log('server:' + data.toString());
        client.publish('/station', {
            data: data.toString(),
            id: PORT
        })
        // socket.write('Hello Client!');
    });

    //监听连接断开事件
    socket.on('end', function () {
        console.log('Client disconnected.');
    });

    socket.on('error', function (err) {
        console.log("Caught flash policy server socket error: ")
        console.log(err.stack)
    })
});

//TCP服务器开始监听特定端口
server.listen(PORT, HOST);